import React, { Component } from 'react'

export default class Cat extends Component {

  state = {
    list: [
        { selected: true, name: "苹果", price: 10, num: 1, id: 0 },
        { selected: false, name: "香蕉", price: 2, num: 1, id: 1 },
        { selected: false, name: "西红柿", price: 11, num: 3, id: 2 },
    ]
}
changeSeleted=(index)=>{
    let {list}=this.state
    list[index].selected=!list[index].selected
    console.log("list",list);
    this.setState({
      list
    })
}
changeNum = (index,n)=>{
  let {list}=this.state
  list[index].num+=n
  this.setState({
    list
  })
}
del = (index)=>{
  let {list}=this.state
  list.splice(index,1)
  this.setState({
    list
  })
}
get total(){
    let count=0
    let {list}=this.state
    list.filter(m=>m.selected).forEach(n=>{
      count+=n.price*n.num
    })
    return count
}
  render() {

    let {list}=this.state ;
    return (
     
      <>
      <table>
          <thead>
          <tr>
              <th><input type="checkbox" /></th>
               <th>商品名</th>
               <th>单价</th>
               <th>数量</th>
               <th>小计</th>
               <th>操作</th>
            </tr>
          </thead>
      <tbody>
             {list.map((item,index)=>{
                return <tr key={item.id}>
                    <td><input onChange={()=>this.changeSeleted(index)} checked={item.selected} type="checkbox" /></td>
                    <td>{item.name}</td>
                    <td>{item.price}</td>
                    <td><button disabled={item.num==1} onClick={()=>this.changeNum(index,-1)}>-</button>{item.num}<button onClick={()=>this.changeNum(index,1)}>+</button></td>
                    <td>{item.num*item.price}</td>
                    <td><button onClick={()=>this.del(index)}>删除</button></td>


                </tr>


             })} 
      </tbody>
      <tfoot>
              <tr>总计:{this.total}</tr>
      </tfoot>
      </table>
      
      
      </>
    )
  }
}
